package com.xssq.config;

import com.alipay.api.AlipayApiException;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.xssq.domain.pay.AliPayBean;
import com.xssq.domain.pay.WxPayBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author xssq
 * @version 1.0.0
 * @date 2023/09/05 04:34:05
 * @saying 你可以不会但你必须得知道
 */
@Configuration
public class PayContext {
    @Resource
    private AliPayBean aliPayBean;
    @Autowired
    WxPayBean wxPayBean;
//    private String notifyUrl;
//    private String refundNotifyUrl;

    @Bean
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(aliPayBean.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(aliPayBean.getAppId())
                    .setAliPayPublicKey(aliPayBean.getPublicKey())
                    .setAppCertPath(aliPayBean.getAppCertPath())
                    .setAliPayCertPath(aliPayBean.getAliPayCertPath())
                    .setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
                    .setCharset("UTF-8")
                    .setPrivateKey(aliPayBean.getPrivateKey())
                    .setServiceUrl(aliPayBean.getServerUrl())
                    .setSignType("RSA2")
                    // 普通公钥方式
                    //.build();
                    // 证书模式
                    .buildByCert();
        }
        AliPayApiConfigKit.putApiConfig(aliPayApiConfig);
        return aliPayApiConfig;
    }

    @Bean
    public WxPayApiConfig getWxApiConfig() {
        WxPayApiConfig apiConfig;

        try {
            apiConfig = WxPayApiConfigKit.getApiConfig(wxPayBean.getAppId());
        } catch (Exception e) {
            apiConfig = WxPayApiConfig.builder()
                    .appId(wxPayBean.getAppId())
                    .mchId(wxPayBean.getMchId())
                    .partnerKey(wxPayBean.getPartnerKey())
                    .certPath(wxPayBean.getCertPath())
                    .domain(wxPayBean.getDomain())
                    .build();
        }
//        notifyUrl = apiConfig.getDomain().concat("/wxPay/payNotify");
//        refundNotifyUrl = apiConfig.getDomain().concat("/wxPay/refundNotify");
        WxPayApiConfigKit.putApiConfig(apiConfig);
        return apiConfig;
    }
}
